/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.skjegstad.mist2.examples;

import com.skjegstad.mist2.IMistSubscriptionListener;
import com.skjegstad.mist2.MistCoreManager;
import com.skjegstad.mist2.datatypes.DataElement;
import com.skjegstad.mist2.events.ExpiredDataElementsEvent;
import com.skjegstad.mist2.exceptions.MistException;
import com.skjegstad.simpleevents.SimpleEvent;
import com.skjegstad.simpleevents.SimpleEventListener;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 *
 * @author magnus
 */
public class MistExample {
    public static void main(String argv[]) throws UnknownHostException, MistException, InterruptedException {
        MistCoreManager mistCore = new MistCoreManager();
        //mistCore.setDebug(true); // Enable debug messages.
        mistCore.enableMulticast(InetAddress.getByName("239.0.0.1"), 1234);
        
        mistCore.start(); // Start network modules and event listeners

        System.out.println("My node identifier is " + mistCore.getMyNodeId().getNodeIdentifier());
        
        // Add subscriber
        mistCore.subscribe("mist.example", new IMistSubscriptionListener() {
            public void deliverMessage(DataElement message) throws MistException {
                System.out.println("Received data element with age " + message.getAge() + " ms and expire time " + message.getExpireTime() + " from node " + message.getSourceNode().getNodeIdentifier() + " ms");
            }
        });

        // Add event listener for expired items
        mistCore.getEventManager().getDataManagerEventPipe().listen(new SimpleEventListener() {
            public void receiveEvent(SimpleEvent event) {
                if (event instanceof ExpiredDataElementsEvent) {
                    ExpiredDataElementsEvent e = (ExpiredDataElementsEvent) event;
                    System.out.println("Expired " + e.getDataElements().size() + " data elements.");
                }
            }
        });
        
        // Publish hello world with 60 second expire time
        mistCore.publish("mist.example", "Hello world".getBytes(), 60 * 1000);
        
        System.out.println("Waiting for 120 seconds.");
        Thread.sleep(120 * 1000);
        
        // Stop background threads and exit
        mistCore.stop();
    }
}
